package com.gulimall.ware.controller;

import com.gulimall.common.exception.BizCodeEnum;
import com.gulimall.common.to.WareSkuLockTo;
import com.gulimall.common.utils.PageUtils;
import com.gulimall.common.utils.R;
import com.gulimall.ware.entity.WareSkuEntity;
import com.gulimall.ware.service.WareSkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 商品库存
 *
 * @author kkk
 * @email 2017809755@qq.com
 * @date 2022-05-17 22:04:35
 */
@RestController
@Slf4j
@RequestMapping("ware/waresku")
public class WareSkuController {
    @Autowired
    private WareSkuService wareSkuService;

    /**
     * 锁定所有的库存信息
     */
    @PostMapping("/lock/order")
    public R orderLockStock(@RequestBody WareSkuLockTo wareSkuLockTo) {
        try {
            boolean hasStock = wareSkuService.orderLockStock(wareSkuLockTo);
        } catch (Exception error) {
            log.error(error.getMessage());
            return R.error(BizCodeEnum.NO_STOCK_EXCEPTION.getCode(), BizCodeEnum.NO_STOCK_EXCEPTION.getMsg());
        }

        return R.ok();
    }

    /**
     * 根据skuId 查出库存信息
     */
    @PostMapping("/stockNum")
    public R getStockBySkuId(@RequestBody List<Long> skuIds) {
        Map<Long, Boolean> result = wareSkuService.queryProductStock(skuIds);

        return R.ok().put("stocks", result);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
//        PageUtils page = wareSkuService.queryPage(params);
        PageUtils page = wareSkuService.queryPageSkuWare(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    //@RequiresPermissions("ware:waresku:info")
    public R info(@PathVariable("id") Long id) {
        WareSkuEntity wareSku = wareSkuService.getById(id);

        return R.ok().put("wareSku", wareSku);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    // @RequiresPermissions("ware:waresku:save")
    public R save(@RequestBody WareSkuEntity wareSku) {
        wareSkuService.save(wareSku);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    //@RequiresPermissions("ware:waresku:update")
    public R update(@RequestBody WareSkuEntity wareSku) {
        wareSkuService.updateById(wareSku);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    //@RequiresPermissions("ware:waresku:delete")
    public R delete(@RequestBody Long[] ids) {
        wareSkuService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
